//
//  MapViewController.m
//  ShanghaiShopping
//
//  Created by KDC on 2019/8/22.
//  Copyright © 2019 KDC. All rights reserved.
//

#import "MapViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "MapTopTableViewCell.h"
#import "CustomAnnotationView.h"
#import "MapBottomView.h"
#import "MyAnnotation.h"

#define MAP_SIZE        6000
#define TopBtnWeight    162


@interface MapViewController () <MKMapViewDelegate, CLLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic , strong) MKMapView *mapView;        ///<地图
@property (nonatomic , strong) MapBottomView *mapBottomView;        ///<地图底部视图

@property (nonatomic , strong) CLLocationManager *locManager;   ///<获得定位
@property (nonatomic , strong) BaseButton *btnTop;   //顶部BTN
@property (nonatomic , strong) UIView *topSelectView;   //顶部选中BTN
@property (nonatomic , strong) UIImageView *arrowsImage;   //箭头

@property (nonatomic , strong) UITableView *topTableView;

@property (nonatomic , strong) NSMutableArray *dataArr;
/**
 当前选中专线
 */
@property (nonatomic , copy) NSString *strSelected;

@property (nonatomic , strong) NSMutableArray *coordinatesArr;//坐标大头针
/**
 手机可用的地图软件
 */
@property (nonatomic , strong) NSMutableArray *availableMaps;
/**
 大头针坐标
 */
@property (nonatomic , assign) CLLocationCoordinate2D endAnno2D;
/**
 得到当前位置
 */
@property (nonatomic , strong) CLLocation *currentLocation;

/**
 首次进入
 */
@property (nonatomic , assign) NSInteger firstOpen;


/**
 底部视图image
 */
@property (nonatomic , copy) NSString *imgUrl;
/**
 底部视图title
 */
@property (nonatomic , copy) NSString *bottomTitle;
/**
 底部视图subTitle
 */
@property (nonatomic , copy) NSString *bottomSubTitle;
/**
 A,B两点的距离
 */
@property (nonatomic , assign) CLLocationDistance distanceAB;

/**
 大头针颜色
 */
@property (nonatomic , copy) NSString *annoColor;



@end

@implementation MapViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.strSelected = @"";
   
    [self initUI];
    //申请用户授权
    [self.locManager requestWhenInUseAuthorization];
    [self.locManager startUpdatingLocation];    //开始更新当前位置信息
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self loadNetData];
    });
}

- (void)initUI {
    [self.view addSubview:self.mapView];
    [self addTopView];
    [self.view addSubview:self.mapBottomView];
}

- (void)addTopView {
    [self.view addSubview:self.topTableView];

    self.btnTop = [[BaseButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - TopBtnWeight) / 2, 47, TopBtnWeight, 38)];
    [self.btnTop setAttributedTitle:[self getAttributedString] forState:UIControlStateNormal];
    self.btnTop.titleLabel.font = FONT(16);
    self.btnTop.layer.cornerRadius = 19;
    [self.btnTop addTarget:self action:@selector(actionTopBtn) forControlEvents:UIControlEventTouchUpInside];
    self.btnTop.backgroundColor = UIColorFromRGB(0xFFFFFF);
    [self.view addSubview:self.btnTop];
}

- (void)loadNetData {

    [PPNetworkHelper POST:URL_getMapLine parameters:nil success:^(id responseObject) {
        NSArray *arr = responseObject[@"retBody"];
        if (IsNotNilArr(arr)) {
            [self.dataArr addObjectsFromArray:responseObject[@"retBody"]];
        }
        [self updateUI];
        [self addAnnotation:0];
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:SXLoadingErrorStr duration:SXLoadingTime];
    }];
}

- (void)mapTap:(UITapGestureRecognizer *)tap {
    self.mapBottomView.hidden = YES;
}

#pragma mark - 添加自定义大头针
- (void)addAnnotation:(NSInteger)index {
    self.coordinatesArr = self.dataArr[index][@"coordinates"];
    
    for (int i = 0; i < self.coordinatesArr.count; i++) {
        MyAnnotation *anno = [[MyAnnotation alloc] initWithAnnotationModelWithDict:self.coordinatesArr[i]];
        [self.mapView addAnnotation:anno];
    }
}

- (void)updateUI {
    self.strSelected = DSStringValue(self.dataArr[0][@"lineName"]);
    
    [self.btnTop setAttributedTitle:[self getAttributedString] forState:UIControlStateNormal];
    [self.topTableView reloadData];
    
    CGFloat height = 33 * self.dataArr.count + 38 + 25;
    self.topTableView.frame = CGRectMake((SCREEN_WIDTH - TopBtnWeight) / 2, 47, TopBtnWeight, height);
}

- (void)actionTopBtn {
    self.topTableView.hidden = !self.topTableView.hidden;
    
    UIImage *image;
    UIColor *color;
    if (self.topTableView.hidden == YES) {
        image = [UIImage imageNamed:@"下滑Y"];
        color = [UIColor blackColor];
    } else {
        image = [UIImage imageNamed:@"下滑N"];
        color = UIColorFromRGB(0x747983);
    }
    NSMutableAttributedString *attributedString = [self appendAttributedString:self.strSelected appendImage:image color:color];
    [self.btnTop setAttributedTitle:attributedString forState:UIControlStateNormal];
}
#pragma mark - MKMapViewDelegate 定位
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    //得到当前位置
    CLLocation *currentLocation = locations.lastObject;
    self.currentLocation = currentLocation;
    //需要将地图的显示区域变小
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(currentLocation.coordinate, MAP_SIZE, MAP_SIZE);
    [_mapView setRegion:region animated:YES];
}
#pragma mark - MKMapViewDelegate 设置大头针 类同cell
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    //用户当前位置大头针
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
//        static NSString *userLocationStyleReuseIndetifier = @"userLocationStyleReuseIndetifier";
//        MKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:userLocationStyleReuseIndetifier];
//        if (annotationView == nil) {
//            annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:userLocationStyleReuseIndetifier];
//        }
//        annotationView.canShowCallout = YES;
//        annotationView.image = ImageNamed(@"位置");
//        return annotationView;
        return nil;
    } else {
        static NSString *reuseIndetifier = @"annotationReuseIndetifier";
        CustomAnnotationView *annotationView = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil) {
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
        }
        MyAnnotation *anno = (MyAnnotation *)annotation;
        annotationView.titleLabel.text = DSStringValue(anno.titleAnno);
        annotationView.frame = CGRectMake(0, 0, 102, 80);
        annotationView.canShowCallout = NO;
        // 设置中心点偏移，使得标注底部中间点成为经纬度对应点
        annotationView.centerOffset = CGPointMake(0, -18);
        return annotationView;
    }
}

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
//    排除当前定位大头针
    if ([view isKindOfClass:[CustomAnnotationView class]]) {
        self.endAnno2D = CLLocationCoordinate2DMake(view.annotation.coordinate.latitude,
                                                    view.annotation.coordinate.longitude);
        CLLocationCoordinate2D startCoor = self.currentLocation.coordinate;;
        CLLocationCoordinate2D endCoor = self.endAnno2D;
        
        CLLocation *locA = [[CLLocation alloc] initWithLatitude:startCoor.latitude longitude:startCoor.longitude];
        CLLocation *locB = [[CLLocation alloc] initWithLatitude:endCoor.latitude longitude:endCoor.longitude];
        //两点距离
        MyAnnotation *anno = (MyAnnotation *)view.annotation;
        self.distanceAB = [locA distanceFromLocation:locB];
        self.imgUrl = DSStringValue(anno.imgUrl);
        self.bottomTitle = DSStringValue(anno.titleAnno);
        self.bottomSubTitle = DSStringValue(anno.subTitleAnno);
        self.mapBottomView.hidden = NO;
        
        CustomAnnotationView *annoView = (CustomAnnotationView *)view;
        annoView.titleLabelColor = self.annoColor;
    }
}

- (void)mapNavigation {
    [self availableMapsApps];
    
    MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
    MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:self.endAnno2D addressDictionary:nil]];
    UIAlertController *alerController = [UIAlertController alertControllerWithTitle:@"选择导航方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"系统地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        toLocation.name = self.bottomTitle;
        [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                       launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,
                                       MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
    }];
    [alerController addAction:action];
    
    for (NSDictionary *dic in self.availableMaps) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:dic[@"name"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSString *URLStr = [dic[@"url"] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:URLStr] options:@{} completionHandler:^(BOOL success) {
                NSLog(@"地图已调用");
            }];
        }];
        [alerController addAction:action];
    }
    WeakSelf;
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //        取消选中正确方式
        StrongSelf;
        for (id <MKAnnotation>annotation in strongSelf.mapView.annotations) {
            [strongSelf.mapView deselectAnnotation:annotation animated:YES];
        }
    }];
    [alerController addAction:actionCancel];
    [self.navigationController presentViewController:alerController animated:YES completion:nil];
}
/**
 识别手机已装的地图app（数组）
 */
- (void)availableMapsApps {
    if (IsNotNilArr(self.availableMaps)) {
        [self.availableMaps removeAllObjects];
    }
    CLLocationCoordinate2D startCoor = self.currentLocation.coordinate;
    CLLocationCoordinate2D endCoor = self.endAnno2D;
    NSString *toName = @"目的地";
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://map/"]]) {
        NSString *urlString = [NSString stringWithFormat:@"baidumap://map/direction?origin=latlng:%f,%f|name:我的位置&destination=latlng:%f,%f|name:%@&mode=driving",
                               startCoor.latitude, startCoor.longitude, endCoor.latitude, endCoor.longitude, toName];
        NSDictionary *dic = @{@"name": @"百度地图",
                              @"url": urlString};
        [self.availableMaps addObject:dic];
    }
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        NSString *urlString = [NSString stringWithFormat:@"iosamap://path?sourceApplication=applicationName&sid=&slat=%f&slon=%f&sname=我的位置&did=&dlat=%f&dlon=%f&dname=%@&dev=0&t=0",startCoor.latitude, startCoor.longitude, endCoor.latitude, endCoor.longitude, toName];
        NSDictionary *dic = @{@"name": @"高德地图",
                              @"url": urlString};
        [self.availableMaps addObject:dic];
    }
}

#pragma mark - tableView 代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 33;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    self.firstOpen = 1;
    //移除需要移除的大头针
    [self.mapView removeAnnotations:self.mapView.annotations];
    self.strSelected = DSStringValue(self.dataArr[indexPath.row][@"lineName"]);
    self.coordinatesArr = self.dataArr[indexPath.row][@"coordinates"];
    [self actionTopBtn];
    self.annoColor = self.dataArr[indexPath.row][@"coordinates"][0][@"color"];
    
    
    [self addAnnotation:indexPath.row];
    
    //需要将地图的显示区域变小
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(self.currentLocation.coordinate, MAP_SIZE, MAP_SIZE);
    [self.mapView setRegion:region animated:YES];
    self.mapBottomView.hidden = YES;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellID = @"MapTopTableViewCell";
    MapTopTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[MapTopTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    NSDictionary *dicData = self.dataArr[indexPath.row];
    NSString *str = DSStringValue(dicData[@"lineName"]);
    NSInteger isHot = [DSStringValue(dicData[@"isHot"]) integerValue];
    NSMutableAttributedString *attStr;
    if (isHot == 1) {
        attStr = [self appendAttributedString:str appendImage:ImageNamed(@"HOT") color:[UIColor blackColor]];
        cell.lbTitle.attributedText = attStr;
    } else if (isHot == 2) {
        attStr = [self appendAttributedString:str appendImage:ImageNamed(@"NEW") color:[UIColor blackColor]];
        cell.lbTitle.attributedText = attStr;
    } else {
        cell.lbTitle.text = str;
    }
    
    return cell;
}
/**
 富文本字符串

 @return 富文本字符串
 */
- (NSMutableAttributedString *)getAttributedString {
    self.strSelected = [self.strSelected stringByAppendingString:@" "];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.strSelected];
    NSTextAttachment *attach = [[NSTextAttachment alloc] init];
    attach.image = ImageNamed(@"下滑Y");
    NSAttributedString *appendStr = [NSAttributedString attributedStringWithAttachment:attach];
    [attributedString appendAttributedString:appendStr];
    return attributedString;
}
/**
 富文本字符串
 
 @return 富文本字符串
 */
- (NSMutableAttributedString *)appendAttributedString:(NSString *)titleStr appendImage:(UIImage *)appendImage color:(UIColor *)color  {
    titleStr = [titleStr stringByAppendingString:@" "];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:titleStr];
    NSTextAttachment *attach = [[NSTextAttachment alloc] init];
    attach.image = appendImage;
    NSAttributedString *appendStr = [NSAttributedString attributedStringWithAttachment:attach];
    [attributedString appendAttributedString:appendStr];
    
    [attributedString addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, attributedString.length)];
    
    return attributedString;
}
#pragma mark - 懒加载
- (CLLocationManager *)locManager {
    if (!_locManager) {
        _locManager = [[CLLocationManager alloc] init];
        _locManager.activityType = CLActivityTypeFitness; //步行导航
        _locManager.delegate = self;
        _locManager.distanceFilter = 1000.0f;//设置距离筛选器
    }
    return _locManager;
}

- (MKMapView *)mapView {
    if (!_mapView) {
        _mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
        _mapView.delegate = self;
        
        if (@available(iOS 11.0, *)) {
            _mapView.mapType = MKMapTypeMutedStandard;
        } else {
            // Fallback on earlier versions
        }
        if (@available(iOS 13.0, *)) {
            _mapView.showsLargeContentViewer = YES;
        } else {
            // Fallback on earlier versions
        }
        _mapView.showsUserLocation = YES;
        _mapView.showsScale = YES;
        _mapView.showsCompass = YES;
        _mapView.showsPointsOfInterest = YES;
        _mapView.showsTraffic = YES;
        _mapView.showsBuildings = YES;

        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(mapTap:)];
        [_mapView addGestureRecognizer:tap];
    }
    return _mapView;
}

- (UITableView *)topTableView {
    if (!_topTableView) {
        UIView *tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, TopBtnWeight, 38)];
        _topTableView = [[UITableView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - TopBtnWeight)/2, 47, TopBtnWeight, 300)];
        _topTableView.delegate = self;
        _topTableView.dataSource = self;
        _topTableView.layer.cornerRadius = 19;
        _topTableView.layer.masksToBounds = YES;
        _topTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _topTableView.hidden = YES;
        _topTableView.tableHeaderView = tableHeaderView;
        _topTableView.backgroundColor = UIColorFromRGB(0xFFFFFF);
        [_topTableView registerNib:[UINib nibWithNibName:@"MapTopTableViewCell" bundle:nil] forCellReuseIdentifier:@"MapTopTableViewCell"];
    }
    return _topTableView;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}

- (NSMutableArray *)coordinatesArr {
    if (!_coordinatesArr) {
        _coordinatesArr = [[NSMutableArray alloc] init];
    }
    return _coordinatesArr;
}

- (NSMutableArray *)availableMaps {
    if (!_availableMaps) {
        _availableMaps = [[NSMutableArray alloc] init];
    }
    return _availableMaps;
}

- (MapBottomView *)mapBottomView {
    if (!_mapBottomView) {
        _mapBottomView = [[MapBottomView alloc] initWithFrame:CGRectMake(ADAPT_W(20), SCREEN_HEIGHT - kTabBarHeight - 25 - 131, SCREEN_WIDTH - ADAPT_W(40), 131)];
    }
    _mapBottomView.hidden = YES;
    _mapBottomView.distance = self.distanceAB;
    _mapBottomView.imageURL = self.imgUrl;
    _mapBottomView.title = self.bottomTitle;
    _mapBottomView.subtitle = self.bottomSubTitle;
    
    WeakSelf;
    _mapBottomView.block = ^{
        StrongSelf;
        [strongSelf mapNavigation];
    };
    return _mapBottomView;
}


@end
